
#include <iostream>
#include <string>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

//Fater process 
//Chile process

int main()
{
    //1. 创建管道
    int fds[2] = {0};
    int n = pipe(fds); //dfs:输出型参数
    if(n != 0)
    {
        std::cerr << "pipe error" << std::endl;
        return 1;
    }
    //至此 管道打开成功

    //子进程写, 父进程读
    //2.创建子进程
    pid_t id = fork();
    if(id < 0)
    {
        std::cerr << "fork error" << std::endl; 
        return 2;
    }
    else if(id == 0)
    {
        //子进程
        //3.关闭不想需要的fd, 关闭read
        close(fds[0]);
        int cnt = 0;
        while(true)
        {
            //子进程进行写
            std::string message = "hello world , i am child";
            
            write(fds[1], message.c_str(), message.size());
            sleep(2);
        }
    }
    else
    {
        //父进程
        close(fds[1]);
        char buffer[1024];
        while(true)
        {
            ssize_t n = ::read(fds[0], buffer, 1024);
            if(n > 0)
            {
                buffer[n] = 0;
                std::cout<<"message : " << buffer << std::endl;
            }
            else if(n == 0)
            {
                //表示写端关闭
                //会读取到返回值0, 表示对端关闭, 也表示读到文件结尾
                std::cout << "n" << n << std::endl;
                std::cout << "child quit ? yes " << std::endl;
                break;
            }
        }
        int status = 0;
        pid_t rid = waitpid(id, &status, 0);
        std::cout << "father wait child success " << rid << "exit code "
        << ((status<<8)&0xFF) << ", exit sig: " << (status & 0x7F) << std::endl;
    }
    return 0;
}